const HASH = 'hash'
let _Vue = null

export default class VueRouter {
  static install (Vue) {
    if (VueRouter.install.installed && _Vue === Vue) {
      return
    }
    VueRouter.install.installed = true
    _Vue = Vue
    Vue.mixin({
      beforeCreate () {
        if (this.$options.router) {
          Vue.prototype.$router = this.$options.router
          this.$options.router.init()
        }
      }
    })
  }

  constructor (options) {
    this.options = options
    this.routeMap = {}
    this.mode = options.mode
    this.data = _Vue.observable({
      current: '/'
    })
  }

  init () {
    this.createRouteMap()
    this.initComponents(_Vue)
    this.initEvent()
  }

  initComponents (Vue) {
    this.refresh()
    const self = this
    Vue.component('router-link', {
      props: {
        to: String
      },
      render (h) {
        return h('a', {
          attrs: {
            href: this.to
          },
          on: {
            click: this.clickHandler
          }
        }, [this.$slots.default])
      },
      methods: {
        clickHandler (e) {
          self.mode === HASH
            ? self.hashChange(this.to)
            : self.historyChange(this.to)
          this.$router.data.current = this.to
          e.preventDefault()
        }
      }
    })
    Vue.component('router-view', {
      render (h) {
        const component = self.routeMap[self.data.current]
        return h(component)
      }
    })
  }

  createRouteMap () {
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component
    })
  }

  historyChange (path) {
    history.pushState({}, '', path)
  }

  hashChange (path) {
    window.location.hash = path
  }

  // 处理浏览器刷新问题
  refresh () {
    this.mode === HASH
      ? this.hashURLHandle()
      : this.data.current = window.location.pathname || '/'
  }

  hashURLHandle () {
    if (!window.location.hash) {
      window.location.hash = '/'
    }
    this.data.current = window.location.hash.slice(1) || '/'
  }

  // 事件初始化
  initEvent () {
    this.mode === HASH
      ? this.initHashEvent()
      : this.initHistoryEvent()
  }

  initHistoryEvent () {
    window.addEventListener('popstate', () => {
      this.data.current = window.location.pathname
    })
  }

  initHashEvent () {
    window.addEventListener('hashchange', () => {
      this.data.current = window.location.hash.slice(1)
    })
  }
}
